<?php
/**
 * Created by PhpStorm.
 * User: yangwang
 * Date: 2024-04-26
 * Time: 19:37
 */

namespace App\Service\Cruise\Shop;


use App\Enums\BaseErrorCode;
use App\Enums\ErrorCode;
use App\Models\Cruise\CruiseShopLicenseRecordsLogModel;
use App\Models\Cruise\CruiseShopLicenseRecordsModel;
use App\Models\Cruise\CruiseShopLicenseResourceRecordsModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsCacheRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\OpenShop\Organization\WarZoneService;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class CruiseShopLicenseRecordsService extends BaseService
{
    public static function cacheKeyOfShopAction(int $shopId): string
    {
        return "REMOTE:DashboardService:cacheKeyOfShopAction:app.shop.config.license:{$shopId}";
    }

    public static function removeRmsCacheOfShopAction($shopId,$beforeErrorNum,$currentErrorNum)
    {
        if ($beforeErrorNum != $currentErrorNum){
            $rmsShopActionCacheKey = self::cacheKeyOfShopAction($shopId);
            return RmsCacheRemote::rmCache([$rmsShopActionCacheKey]);
        }
        return [];
    }

    public static function getInfo(int $shopId, bool $isWeb = false): array
    {
        $licenseModel = CruiseShopLicenseRecordsModel::query()
                                                     ->with('resourceRel')
                                                     ->where('shopId', $shopId)
                                                     ->first();

        $formatList = [];

        if (empty($licenseModel)) {
            self::throwErr('license records 数据异常', BaseErrorCode::$BASE_CODE_DETAIL_FAIL);
        }

        foreach ($licenseModel->resourceRel ?: [] as $resource) {
            $content                     = json_decode($resource->contents ?: '[]', '1');
            $licenseEndDateIsForever     = CruiseShopLicenseResourceRecordsModel::licenseIsForever(
                $resource->licenseEndDate
            ) ? 1 : 0;
            $formatList[$resource->type] = array_merge(
                ['id' => $resource->id],
                self::formatInfoData(
                    picturePath($resource->url),
                    $resource->licenceNumber,
                    $resource->name,
                    !$licenseEndDateIsForever ? date('Y-m-d', $resource->licenseEndDate) : '',
                    $licenseEndDateIsForever,
                    $content['businessScope'] ?? '',
                    $resource->causeOfRejection,
                    $resource->remark,
                    $resource->status,
                    (!$isWeb && $resource->status == CruiseShopLicenseRecordsModel::STATUS_PENDING)
                        ? '审核中'
                        : CruiseShopLicenseRecordsModel::STATUS_MAP[$resource->status],
                    $content['mainBusiness'] ?? ''
                )
            );
        }

        return [
            'businessLicense' => $formatList[CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE] ?? self::formatInfoData(),
            'foodLicense'     => $formatList[CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE] ?? self::formatInfoData(),
        ];
    }

    public static function formatInfoData(
        $url = '',
        $licenseNumber = '',
        $name = '',
        $licenseEndDate = '',
        $licenseEndDateIsForever = 0,
        $businessScope = '',
        $causeOfRejection = '',
        $remark = '',
        $status = CruiseShopLicenseRecordsModel::STATUS_LACK,
        $statusDesc = CruiseShopLicenseRecordsModel::STATUS_MAP[CruiseShopLicenseRecordsModel::STATUS_LACK],
        $mainBusiness = ''
    ): array {
        return [
            'url'                     => $url,
            'licenceNumber'           => $licenseNumber,
            'name'                    => $name,
            'licenseEndDate'          => $licenseEndDate,
            'licenseEndDateIsForever' => $licenseEndDateIsForever,
            'businessScope'           => $businessScope,
            'causeOfRejection'        => ($status == CruiseShopLicenseRecordsModel::STATUS_REJECT) ? $causeOfRejection : '',
            'remark'                  => $remark,
            'status'                  => $status,
            'statusDesc'              => $statusDesc,
            'mainBusiness'            => $mainBusiness
        ];
    }

    public static function initShopLicense(int $shopId)
    {
        CruiseShopLicenseRecordsModel::query()->firstOrCreate([
            'shopId' => $shopId,
        ], [
            'status' => CruiseShopLicenseRecordsModel::STATUS_LACK
        ]);
    }

    /**
     * @param int $userId
     * @param int $shopId
     * @param array $businessLicense
     * @param array $foodLicense
     * @return bool
     */
    public static function update(int $userId, int $shopId, array $businessLicense, array $foodLicense, bool $isWeb = false): bool
    {
        $record = CruiseShopLicenseRecordsModel::query()
                                               ->where('shopId', $shopId)
                                               ->first();
        if (empty($record)) {
            self::throwErr('门店记录异常', BaseErrorCode::$BASE_CODE_DETAIL_FAIL);
        }

        $lastShopLicenseStatus = self::getShopLicenseStatusByShopId($shopId);

        $ids = [];
        if ($id = $businessLicense['id'] ?? 0) {
            $ids[] = $id;
        }
        if ($id = $foodLicense['id'] ?? 0) {
            $ids[] = $id;
        }

        $resourceList = [];
        if ($ids) {
            $resourceList = CruiseShopLicenseResourceRecordsModel::query()
                                                                 ->whereIn('id', $ids)
                                                                 ->get()
                                                                 ->keyBy('id');
        }

        $insertList = $changeStatusList = $logInsertList = [];
        $errors     = [];
        $statusList = [];
        foreach (
            [
                CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE => $businessLicense,
                CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE     => $foodLicense
            ] as $type => $item
        ) {
            $isChange = false;
            $_id = $item['id'] ?? 0;

            $ocrResult = $item['ocrResult'] ?? [];
            $contents  = [];
            //如果是用户更新,没有重新识别，把原来的ocr拉出来放到新的里面
            if (($model = $resourceList[$_id] ?? []) && empty($ocrResult)) {
                $contents  = json_decode($model->contents ?: '[]', 1);
                $ocrResult = $isWeb ? ($contents['ocrResult'] ?? []) : [];
            }

            $legalPerson = $licenseStartDate = '';
            $licenseNumber = $licenseName = '';
            if ($ocrResult) {
                switch ($type) {
                    case CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE:
                        $legalPerson      = $ocrResult['LegalPerson'] ?? '';
                        $licenseStartDate = !empty($ocrResult['establishDate'])
                            ? strtotime($ocrResult['establishDate'])
                            : 0;
                        $licenseNumber = empty($item['licenceNumber'])
                            ? $ocrResult['RegisterNumber'] ?? ''
                            : $item['licenceNumber'];
                        $licenseName = $ocrResult['Name'] ?? '';
                        break;
                    case CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE:
                        $legalPerson      = $ocrResult['legalRepresentative'] ?? '';
                        $licenseStartDate = !empty($ocrResult['issueDate'])
                            ? strtotime($ocrResult['issueDate'])
                            : 0;
                        $licenseNumber = empty($item['licenceNumber'])
                            ? $ocrResult['licenceNumber'] ?? ''
                            : $item['licenceNumber'];
                        $licenseName = $ocrResult['producerName'] ?? '';
                        break;
                }
            }

            $licenseEndDate = $item['licenseEndDateIsForever']
                ? strtotime(CruiseShopLicenseResourceRecordsModel::LICENSE_FOREVER_DATE)
                : strtotime($item['licenseEndDate']);

            if (!CruiseShopLicenseResourceRecordsModel::licenseIsForever($licenseEndDate) && $licenseEndDate < time() && !$isWeb) {
                $errors[] = CruiseShopLicenseResourceRecordsModel::TYPE_MAP[$type] . "已经到期";
                continue;
            }

            $status = CruiseShopLicenseRecordsModel::STATUS_PENDING;
            if ($isWeb){
                //时间有变更
                if (optional($model)->licenseEndDate != $licenseEndDate){
                    if ($licenseEndDate < time()){
                        $status = CruiseShopLicenseRecordsModel::STATUS_EXPIRED;
                    } else {
                        $status = CruiseShopLicenseRecordsModel::STATUS_PENDING;
                    }
                } else {
                    $status = optional($model)->status ?: CruiseShopLicenseRecordsModel::STATUS_PENDING;
                }
            }

            $formatItem = [
                'shopId'           => $shopId,
                'url'              => trim(parse_url($item['url'])['path'], '/'),
                'type'             => $type,
                'status'           => $status,
                'causeOfRejection' => (CruiseShopLicenseRecordsModel::STATUS_REJECT == $status)
                    ? (optional($model)->causeOfRejection ?: '')
                    : '',
                'remark'           => (CruiseShopLicenseRecordsModel::STATUS_REJECT == $status)
                    ? (optional($model)->remark ?: '')
                    : '',
                'legalPerson'      => $legalPerson,//
                'licenseStartDate' => $licenseStartDate,//
                'licenceNumber'    => $licenseNumber,
                'name'             => $item['name'] ?? '',
                'licenseEndDate'   => $licenseEndDate,
                'contents'         => [
                    'businessScope'     => $item['businessScope'] ?? '',
                    'mainBusiness'      => $item['mainBusiness'] ?? '',
                    'licenseName'       => $licenseName,
                    'productionAddress' => $ocrResult['productionAddress'] ?? '',//只有食品经营许可证有
                    'ocrResult'         => $ocrResult,
                ],
                'createdByUid'     => $userId,
                'createdAt'        => time(),
                'updatedByUid'     => $userId,
                'updatedAt'        => time(),
            ];

            //对比是否变更
            if (optional($model)->url != $formatItem['url']
                || optional($model)->name != $formatItem['name']
                || optional($model)->licenseEndDate != $licenseEndDate
                || ($contents['mainBusiness'] ?? '') != ($formatItem['contents']['mainBusiness'] ?? '')
                || ($contents['businessScope'] ?? '') != ($formatItem['contents']['businessScope'] ?? '')
            ) {
                $isChange = true;
            }

            $formatItem['contents'] = json_encode($formatItem['contents'], JSON_UNESCAPED_UNICODE);
            $statusList[] = $status;
            if ($isChange) {
                $insertList[]    = $formatItem;
                $logInsertList[] = [
                    'shopId'      => $shopId,
                    'type'        => $type,
                    'operateType' => $isWeb
                        ? CruiseShopLicenseRecordsLogModel::OPERATE_TYPE_INNER
                        : CruiseShopLicenseRecordsLogModel::OPERATE_TYPE_MERCHANT,
                    'actionType'  => CruiseShopLicenseRecordsLogModel::ACTION_TYPE_CHANGE_INFO,
                ];
            } else {
                $changeStatusList[] = $formatItem;
            }
        }

        if ($errors) {
            self::throwErr(join(';', $errors), BaseErrorCode::$BASE_CODE_INSERT_FAIL);
        }

        //两个都没变更
        if (count($changeStatusList) == 2) {
            return true;
        }

        DB::beginTransaction();
        try {
            $status = CruiseShopLicenseRecordsModel::getStatus($statusList[0],$statusList[1]);
            //record
            CruiseShopLicenseRecordsModel::query()->where('shopId', $shopId)->update([
                'status'                 => $status,
                'merchantUpdatedAtByUid' => $userId,
                'merchantUpdatedAt'      => time(),
                'updatedByUid'           => time(),
                'updatedAt'              => time(),
            ]);
            //log   有id上传、否则更新
            foreach ($logInsertList as $logOne) {
                CruiseShopLicenseRecordsLogModel::query()->create($logOne);
            }

            if ($changeStatusList) {
                foreach ($changeStatusList as $update) {
                    CruiseShopLicenseResourceRecordsModel::query()
                                                         ->where('shopId', $shopId)
                                                         ->where('type', $update['type'])
                                                         ->update([
                                                             'status'       => $update['status'],
                                                             'updatedByUid' => $update['updatedByUid'],
                                                             'updatedAt'    => $update['updatedAt']
                                                         ]);
                }
            }

            if ($insertList) {
                $types = array_column($insertList, 'type');
                //删掉原来的
                CruiseShopLicenseResourceRecordsModel::query()
                                                     ->where('shopId', $shopId)
                                                     ->whereIn('type', $types)
                                                     ->update(['isDeleted' => 1]);
                CruiseShopLicenseResourceRecordsModel::query()->insert($insertList);
            }

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            self::throwErr('更新数据异常,请稍后重试', BaseErrorCode::$BASE_CODE_INSERT_FAIL);
        }

        $currentShopLicenseStatus = self::getShopLicenseStatusByShopId($shopId);
        self::removeRmsCacheOfShopAction($shopId,$lastShopLicenseStatus['num'],$currentShopLicenseStatus['num']);

        return true;
    }

    public static function list(
        $pageSize,
        $pageNum,
        $shopIds = '',
        $dimCode = '',
        $shopStatus = null,
        $status = null,
        $councilorId = 0,
        $merchantUpdatedAtStart = '',
        $merchantUpdatedAtEnd = '',
        $cruiseAtStart = '',
        $cruiseAtEnd = '',
        $activityDays = 0,
        $orderBy = [],
        $export = false
    ): array {
        $query = CruiseShopLicenseRecordsModel::query()
                                              ->leftJoin(
                                                  (new ShopModel())->getTable() . ' as shop',
                                                  (new CruiseShopLicenseRecordsModel())->getTable() . '.shopId',
                                                  '=', 'shop.id'
                                              )
                                              ->leftJoin(
                                                  (new GuanyuanSyncShopListModel())->getTable() . " as gShop",
                                                  'shop.id', '=', 'gShop.shopId'
                                              )
                                              ->when($shopIds, function ($query) use ($shopIds) {
                                                  $_shopIds = explode(',', $shopIds);
                                                  $query->whereIn(
                                                      (new CruiseShopLicenseRecordsModel())->getTable() . '.shopId',
                                                      $_shopIds
                                                  );
                                              })
                                              ->when($dimCode, function ($query) use ($dimCode) {
                                                  if (is_numeric($dimCode)) {
                                                      $query->where('shop.shopCode', $dimCode);
                                                  } elseif (is_string($dimCode)) {
                                                      $query->where('shop.name', 'like', '%' . $dimCode . '%');
                                                  }
                                              })
                                              ->when($shopStatus, function ($query) use ($shopStatus) {
                                                  $statusArr = explode(',', $shopStatus);
                                                  $query->whereIn('gShop.status', $statusArr);
                                              })
                                              ->when(isset($status) && $status !== '', function ($query) use ($status) {
                                                  $statusArr = explode(',', $status);
                                                  $query->whereIn(
                                                      (new CruiseShopLicenseRecordsModel())->getTable() . '.status',
                                                      $statusArr
                                                  );
                                              })
                                              ->when($councilorId, function ($query) use ($councilorId) {
                                                  $query->where('shop.councilorId', $councilorId);
                                              })
                                              ->when($merchantUpdatedAtStart && $merchantUpdatedAtEnd,
                                                  function ($query) use (
                                                      $merchantUpdatedAtStart,
                                                      $merchantUpdatedAtEnd
                                                  ) {
                                                      /** @var Builder $query */
                                                      $query->whereBetween(
                                                          'merchantUpdatedAt',
                                                          [
                                                              Carbon::parse($merchantUpdatedAtStart)
                                                                    ->startOfDay()->timestamp,
                                                              Carbon::parse($merchantUpdatedAtEnd)
                                                                    ->endOfDay()->timestamp
                                                          ]
                                                      );
                                                  })
                                              ->when($cruiseAtStart && $cruiseAtEnd,
                                                  function ($query) use ($cruiseAtStart, $cruiseAtEnd) {
                                                      /** @var Builder $query */
                                                      $query->whereBetween(
                                                          'merchantUpdatedAt',
                                                          [
                                                              Carbon::parse($cruiseAtStart)->startOfDay()->timestamp,
                                                              Carbon::parse($cruiseAtEnd)->endOfDay()->timestamp
                                                          ]
                                                      );
                                                  })
                                              ->when($orderBy, function ($query) use ($orderBy) {
                                                  if ($orderBy['merchantUpdatedAt'] ?? []) {
                                                      $query->orderBy('merchantUpdatedAt',
                                                          $orderBy['merchantUpdatedAt']);
                                                  }
                                                  if ($orderBy['cruiseAt'] ?? []) {
                                                      $query->orderBy('cruiseAt', $orderBy['cruiseAt']);
                                                  }
                                              })
                                              ->when($activityDays, function ($query)use ($activityDays){
                                                    $query->where(
                                                        'gShop.lastActivityAt','>',
                                                        Carbon::now()->subDays($activityDays)->timestamp
                                                    );
                                              })
                                              ->groupBy('shopId')
                                              ->select([
                                                  (new CruiseShopLicenseRecordsModel())->getTable() . ".*",
                                                  'shop.shopCode',
                                                  'shop.name',
                                                  'shop.councilorId',
                                                  'shop.addressPrefix',
                                                  'shop.province',
                                                  'gShop.status as gStatus',
                                              ]);

        if ($export) {
            $paginate = $query->get();
            $list     = $paginate;
        } else {
            $paginate = $query->paginate($pageSize, ['*'], $pageName = 'page', $pageNum);
            $list     = collect($paginate->items());
        }

        $resourceList = [];
        foreach ($list->chunk(500) as $listCollection) {
            $shopIds = $listCollection->pluck('shopId')->toArray();
            if ($shopIds) {
                $resources    = CruiseShopLicenseResourceRecordsModel::query()
                                                                     ->whereIn('shopId', $shopIds)
                                                                     ->get()
                                                                     ->toArray();
                $resourceList = array_merge($resourceList, $resources);
            }
        }
        $resourceList = collect($resourceList)->groupBy('shopId')->toArray();

        $userIds = $list->pluck('councilorId')->unique()->toArray();

        $userIds = array_filter($userIds);

        $users = $userIds
            ? array_column(RmsUserRemote::getRmsUserByIds($userIds, ['id', 'username']), null, 'id')
            : [];

        $formatDistrictList = [];
        if ($export){
            $warZoneDistrictList = WarZoneService::getWarZoneDistrictList();
            foreach ($warZoneDistrictList as $item) {
                foreach ($item['provinceList'] ?? [] as $_item) {
                    $provinceCode                                 = $_item['provinceCode'];
                    $formatDistrictList[$provinceCode]            = $_item;
                    $formatDistrictList[$provinceCode]['warZone'] = $item['name'];
                }
            }
        }

        return [
            'pageSize' => $paginate instanceof Paginator ? $paginate->perPage() : null,
            'pageNum'  => $paginate instanceof Paginator ? $paginate->currentPage() : null,
            'count'    => $paginate instanceof Paginator ? $paginate->total() : null,
            'list'     => $list->map(function ($item) use ($users, $resourceList,$formatDistrictList) {
                $councilorName = $users[$item->councilorId]['username'] ?? '';

                $businessLicenseStatus = $foodLicenseStatus = CruiseShopLicenseRecordsModel::STATUS_MAP[CruiseShopLicenseRecordsModel::STATUS_LACK];

                $resourceItems = array_values($resourceList[$item->shopId] ?? []);
                $mainBusiness  = $businessScope = '';
                foreach ($resourceItems as $resourceItem) {
                    $type   = $resourceItem['type'];
                    $status = $resourceItem['status'];
                    if ($type == CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE) {
                        $businessLicenseStatus = CruiseShopLicenseRecordsModel::STATUS_MAP[$status];
                    }

                    if ($type == CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE) {
                        $foodLicenseStatus = CruiseShopLicenseRecordsModel::STATUS_MAP[$status];
                        $contents          = json_decode($resourceItem['contents'] ?? '', 1);
                        $mainBusiness      = $contents['mainBusiness'] ?? '';
                        $businessScope     = $contents['businessScope'] ?? '';
                    }
                }
                $addressPrefixArr = [];
                if ($item->addressPrefix) {
                    $addressPrefixArr = explode('-', $item->addressPrefix);
                }

                return [
                    'id'                    => $item->id,
                    'shopId'                => $item->shopId,
                    'shopCode'              => $item->shopCode,
                    'name'                  => $item->name,
                    'shopStatus'            => $item->gStatus ?: '',
                    'addressPrefix'         => $item->addressPrefix ?: '',
                    'warZone'               => $formatDistrictList[$item->province]['warZone'] ?? '',
                    'provinceName'          => $addressPrefixArr[0] ?? '',
                    'cityName'              => $addressPrefixArr[1] ?? '',
                    'districtName'          => $addressPrefixArr[2] ?? '',
                    'councilorName'         => $councilorName,
                    'status'                => CruiseShopLicenseRecordsModel::STATUS_MAP[$item->status],
                    'businessLicenseStatus' => $businessLicenseStatus,
                    'foodLicenseStatus'     => $foodLicenseStatus,
                    'mainBusiness'          => $mainBusiness,
                    'businessScope'         => $businessScope,
                    'merchantUpdatedAt'     => $item->merchantUpdatedAt ? date('Y-m-d H:i:s',
                        $item->merchantUpdatedAt) : '',
                    'canAudit'              => ($item->status == CruiseShopLicenseRecordsModel::STATUS_LACK) ? 0 : 1,
                    'cruiseAt'              => $item->cruiseAt ? date('Y-m-d H:i:s', $item->cruiseAt) : '',
                ];
            })->toArray()
        ];

    }

    public static function cruiseInfo(int $shopId): array
    {
        $next     = CruiseShopLicenseRecordsModel::query()
                                                 ->where('shopId', '!=', $shopId)
                                                 ->where(
                                                     'status', CruiseShopLicenseRecordsModel::STATUS_PENDING
                                                 )
                                                 ->first();
        $shopInfo = ShopModel::query()->where('id', $shopId)->first();

        if (empty($shopInfo)) {
            self::throwErr('门店信息异常', BaseErrorCode::$BASE_CODE_DETAIL_FAIL);
        }

        $resourceInfo =  self::getInfo($shopId,true);
        $recordStatus = CruiseShopLicenseRecordsModel::getStatus(
            $resourceInfo['businessLicense']['status'],
            $resourceInfo['foodLicense']['status'],
        );

        $canAudit = in_array($recordStatus, [
                CruiseShopLicenseRecordsModel::STATUS_LACK,
                CruiseShopLicenseRecordsModel::STATUS_EXPIRED
            ]
        ) ? 0 : 1;
        return [
            'shopName'   => "{$shopInfo->shopCode} {$shopInfo->name}",
            'info'       => $resourceInfo,
            'nextShopId' => $next ? $next->shopId : null,
            'canAudit'   => $canAudit
        ];
    }

    public static function cruiseSubmit(int $userId, int $shopId, array $businessLicense, array $foodLicense): array
    {
        $status = CruiseShopLicenseRecordsModel::getStatus(
            $businessLicense['auditStatus'],
            $foodLicense['auditStatus']
        );

        $lastShopLicenseStatus = self::getShopLicenseStatusByShopId($shopId);

        $insertLog = [];
        $current   = time();

        foreach (
            [
                CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE => $businessLicense,
                CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE     => $foodLicense
            ] as $type => $auditItem
        ) {

            CruiseShopLicenseResourceRecordsModel::query()->where('id', $auditItem['id'])
                                                 ->update([
                                                     'status'           => $auditItem['auditStatus'],
                                                     'causeOfRejection' => $auditItem['causeOfRejection'] ?? '',
                                                     'remark'           => $auditItem['remark'] ?? '',
                                                     'cruiseAt'         => time(),
                                                     'cruiseAtByUid'    => $userId,
                                                     'updatedAt'        => time(),
                                                     'updatedByUid'     => $userId,
                                                 ]);

            $remark = $auditItem['causeOfRejection'];
            if ($auditItem['remark'] ?? ''){
                $remark .= ":".$auditItem['remark'];
            }

            $insertLog[] = [
                'shopId'       => $shopId,
                'type'         => $type,
                'operateType'  => CruiseShopLicenseRecordsLogModel::OPERATE_TYPE_INNER,
                'actionType'   => CruiseShopLicenseRecordsModel::STATUS_APPROVED == $auditItem['auditStatus']
                    ? CruiseShopLicenseRecordsLogModel::ACTION_TYPE_AUDIT_APPROVED
                    : CruiseShopLicenseRecordsLogModel::ACTION_TYPE_AUDIT_REJECT,
                'createdAt'    => $current,
                'createdByUid' => $userId,
                'updatedAt'    => $current,
                'updatedByUid' => $userId,
                'remark'       => $remark,
            ];
        }

        CruiseShopLicenseRecordsModel::query()->where('shopId', $shopId)
                                     ->update([
                                         'status'        => $status,
                                         'cruiseAt'      => $current,
                                         'cruiseAtByUid' => $userId,
                                         'updatedAt'     => $current,
                                         'updatedByUid'  => $current
                                     ]);

        CruiseShopLicenseRecordsLogModel::query()->insert($insertLog);

        $currentShopLicenseStatus = self::getShopLicenseStatusByShopId($shopId);
        self::removeRmsCacheOfShopAction($shopId,$lastShopLicenseStatus['num'],$currentShopLicenseStatus['num']);

        return self::cruiseInfo($shopId);
    }

    public static function getShopLicenseStatusByShopId(int $shopId)
    {
        return collect(self::getShopLicenseStatus([$shopId]))->where('shopId',$shopId)->first();
    }

    public static function getShopLicenseStatus(array $shopIds): array
    {
        $resourceList = CruiseShopLicenseResourceRecordsModel::query()
                                                             ->whereIn('shopId', $shopIds)
                                                             ->get()
                                                             ->groupBy('shopId')
                                                             ->toArray();

        $statusList = [];
        foreach ($shopIds as $shopId) {
            $num = 0;

            $resource = array_values($resourceList[$shopId] ?? []);

            $status1 = $resource[0]['status'] ?? CruiseShopLicenseRecordsModel::STATUS_LACK;
            $status2 = $resource[1]['status'] ?? CruiseShopLicenseRecordsModel::STATUS_LACK;

            if (!in_array($status1, [
                CruiseShopLicenseRecordsModel::STATUS_PENDING,
                CruiseShopLicenseRecordsModel::STATUS_APPROVED
            ])) {
                $num += 1;
            }
            if (!in_array($status2,
                [CruiseShopLicenseRecordsModel::STATUS_PENDING, CruiseShopLicenseRecordsModel::STATUS_APPROVED]
            )) {
                $num += 1;
            }

            if ($num > 2) {
                $num = 2;
            }

            $statusList[] = [
                'shopId'     => $shopId,
                'num'        => $num,
                'showStatus' => (bool)$num
            ];
        }

        return $statusList;
    }
}